<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_synchro_Synchronizer
{
	private static $instance;
	
	/**
	 * @return f_synchro_Synchronizer
	 */
	private function __construct()
	{
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return f_synchro_Synchronizer
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Synchronize a server by rsync
	 *
	 * @param string $serverSection section in config.prefix.ini
	 * @param boolean $dryRun must run in dry mode by default
	 * @param boolean $ftp if true transfert by ftp rather than rsync
	 */
	public function rsyncServer($serverSection = "Production", $dryRun = true)
	{
		$config = f_loader_Config::getInstance()->getParameters($serverSection);

		$excludeFile = FRAMEWORK_HOME.DS."synchro".DS."syncExclude";
		
		$baseDir = BASE_DIR;
		
		$opt = "";
		
		if($dryRun)
		{
			$opt = "n";
		}
		
		passthru("rsync -ravz".$opt." --stats --delete --force --exclude-from=".$excludeFile." --ignore-errors ".BASE_DIR.DS."."." ".$config['user']."@".$config['host'].":".$config['dir']);
	}
	
	/**
	 * Synchronize a server by ftp
	 *
	 * @param string $serverSection section in config.prefix.ini
	 * @param boolean $dryRun must run in dry mode by default
	 * @param string $password ftp password
	 */	
	public function ftpSync($serverSection = "Production", $dryRun = true, $password)
	{
		$config = f_loader_Config::getInstance()->getParameters($serverSection);
		
		$opt = "";
		
		if($dryRun)
		{
			$opt = "--dry-run";
		}
		
		passthru('lftp -u '.$config['user'].','.$password.' '.$config['host'].' -e "mirror '.$opt.' -vvv -e -R -x .*svn.* -x .*log.* -x ^.cache/$ -x ^.settings/$ -x ^.project$ -x ^webapp/cache/templates_c/(.*).php$ -x ^webapp/cache/(.*).html$ '.BASE_DIR.' web ; quit"');
	}
}